/*
 * @Author: zhiming
 * @Date: 2020-07-20 14:56:16
 * @LastEditTime: 2020-08-04 17:32:54
 * @LastEditors: Please set LastEditors
 * @Description: 工具函数类
 * @FilePath: \shopping_mall_app\src\assets\js\utils\index.js
 */
import Echo from '../libs/echo.js';
import config from '../../js/conf/config';
import action from '../../../store/actions/index';
import * as Request from '../../../services/user/index';

//获取路由参数
export function localParam (search, hash) {
    search = search || window.location.search;
    hash = hash || window.location.hash;
    var fn = function(str, reg) {
        if (str) {
            var data = {};
            str.replace(reg, function($0, $1, $2, $3) {
                data[$1] = $3;
            });
            return data;
        }
    };
    return {
        search : fn(search, new RegExp("([^?=&]+)(=([^&]*))?", "g")) || {},
        hash : fn(hash, new RegExp("([^#=&]+)(=([^&]*))?", "g")) || {}
    };
}

//页面置顶
export function setScrollTop(val=0){
    setTimeout(()=>{
        document.body.scrollTop=val;
        document.documentElement.scrollTop=val;
    },300);
}

//图片懒加载
export function lazyImg(){
    Echo.init({
        offset: 50, //离可视区域多少像素的图片可以被加载
        throttle: 0 //图片延迟多少毫秒加载
    });
}

//页面跳转
export function goPage(url){
    this.props.history.push(window.base.config.path+url);
}

//数据深拷贝
export function deepClone(obj, hash = new WeakMap()){
    if (obj === null) return obj; // 如果是null或者undefined我就不进行拷贝操作
    if (obj instanceof Date) return new Date(obj);
    if (obj instanceof RegExp) return new RegExp(obj);
    // 可能是对象或者普通的值  如果是函数的话是不需要深拷贝
    if (typeof obj !== "object") return obj;
    // 是对象的话就要进行深拷贝
    if (hash.get(obj)) return hash.get(obj);
    let cloneObj = new obj.constructor();
    // 找到的是所属类原型上的constructor,而原型上的 constructor指向的是当前类本身
    hash.set(obj, cloneObj);
    // eslint-disable-next-line
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
        // 实现一个递归拷贝
        cloneObj[key] = deepClone(obj[key], hash);
        }
    }
    return cloneObj;
}

//组织冒泡事件
export function preventBubble(e){
    e.stopPropagation();
}

//处理商品属性数据
export function handleAttrData(data, itemName){
    if(data && data.length > 0){
        data.map(item => {
            item.checked = true;
            item[itemName].length > 0 && item[itemName].map(ktem => ktem.checked = false);
        });
    }
    return data;
}

//处理分类数据
export function hanleClassifyData(data){
    data.map(item => item.checked = false);
    return data;
}

//重置商品数据
export function setResetData(data){
    data.items.map(item => {
        if(item.checked){ item.checked = false }
    });
    return data;
}

//会员登录认证
export function authLogin(props){
    const { uid, authToken } = props.user;
    Request.authLogin({ uid, auth_token: authToken }).then(res => {
        if(res.code !== 200 ){
            props.dispatch(action.user.outLogin());
            props.history.replace(config.path+'login/index');
        }
    });
}
